package main;

import javacard.framework.APDU;
import javacard.framework.ISO7816;
import javacard.framework.OwnerPIN;

public class Wallet {
	private OwnerPIN pin = new OwnerPIN((byte)3, (byte)6);
	public static final byte DEPOSIT_INS = 0x01;
	public static final byte WITHDRAWL_INS = 0x02;
	public static final byte CHECK_MONEY_INS = 0x03;
	private final short MAX_MONEY = 30000;

	private short balance = 0;
	public Wallet(){
		this.pin.reset();
		this.balance = 0;
	}

	public void deposit(APDU apdu){
		byte[] buffer = apdu.getBuffer();
		short money;
		money = (short)(buffer[ISO7816.OFFSET_P1]*256 + buffer[ISO7816.OFFSET_P2]);
		if(this.balance + money <= this.MAX_MONEY){
			this.balance += money;
		}
		buffer[0] = (byte) (this.balance >> 8);
		buffer[1] = (byte) (this.balance & 0xff);
		apdu.setOutgoingAndSend((short)0, (short)2);
	}

	public void withdrawl(APDU apdu){
		byte[] buffer = apdu.getBuffer();
		short money = 0;
		money = (short)(buffer[ISO7816.OFFSET_P1]*256 + buffer[ISO7816.OFFSET_P2]);
		if(this.balance - money >= 0){
			this.balance -= money;
		}
		buffer[0] = (byte) (this.balance >> 8);
		buffer[1] = (byte) (this.balance & 0xff);
		apdu.setOutgoingAndSend((short)0, (short)2);
	}

	public void checkBalance(APDU apdu){
		byte[] buffer = apdu.getBuffer();
		buffer[0] = (byte) (this.balance >> 8);
		buffer[1] = (byte) (this.balance & 0xff);
		apdu.setOutgoingAndSend((short)0, (short)2);
	}

}
